package org.adream.account.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DateUtils {
	
	private final static Logger logger = LoggerFactory.getLogger(DateUtils.class);

	/**
	 * 格式化日期格式
	 * @param timestamp
	 * @param format
	 * @return
	 */
	public static String format(long timestamp, String format) {
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		return sdf.format(new Date(timestamp));
	}

	/**
	 * 验证日期是否有效
	 * @param date
	 * @param format(yyyy/MM/dd HH:mm)
	 * @return
	 */
	public static boolean isValidDate(String date, String format) {
		boolean convertSuccess = true;
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		try {
			// set false 2-30 这种格式不能接收
			sdf.setLenient(false);
			sdf.parse(date);
		} catch (ParseException e) {
			// 如果throw java.text.ParseException或者NullPointerException，就说明格式不对
			convertSuccess = false;
		}
		return convertSuccess;
	}

	/**
	 * 日期格式转换
	 * @param date
	 * @param format
	 * @return
	 */
	public static String parseDateString(String date, String format) {
		String resultString = null;
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		try {
			Date d = sdf.parse(date);
			resultString = sdf.format(d);
		} catch (ParseException e) {
			resultString = null;
		}
		return resultString;
	}
	
	/**
	 * 时间格式字符串转为日期格式
	 * @param dateString
	 * @param format
	 * @return
	 */
	public static Date string2Date(String dateString, String format) {
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		Date date = null;
		try {
			date = sdf.parse(dateString);
		} catch (ParseException e) {
			logger.warn("字符串转时间类型出错:" + e.getMessage());
			date = null;
		}
		return date;
	}

	/**
	 * 判断时间格式字符串是否落后现在
	 * 抛出错误 不做处理
	 * 
	 * @param dateString
	 * @param sdf
	 * @return
	 * @throws ParseException
	 */
	public static boolean isAfter(String dateString, SimpleDateFormat sdf) throws ParseException {
		Date date = sdf.parse(dateString);
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		Date now = calendar.getTime();
		if (date.after(now)) {
			return true;
		} else {
			return false;
		}
	}
}